<template>
	<view class="container home-wrap" :style="{ 'background':'#fff'}">
		<shopro-navbar :isBack="true" :background="{'background':'#fff'}">
			<text slot="content" class="u-flex u-flex-center u-flex-items-center" style="color: #000; width: 85%; text-align: center;padding-left: 20rpx;height: 100%;">备考资料</text>
		</shopro-navbar>
		<!-- Tab栏 -->
		<view class="tab-bar">
			<view v-for="(item, index) in tabs" :key="index" :class="['tab-item', { active: currentTab === index }]" @click="onTabChange(item,index)">
				{{ item.name }}
			</view>
		</view>
		<!-- 资料类型筛选 -->
		<view class="subject-select">
			<text>资料类型</text>
			<picker class="picker u-flex u-flex-around" :range="filterOptions" range-key="label" @change="onFilterChange">
				<text class="filter-value">{{ filterOptions[selectedFilter].label }}</text>
				<text class="picker-btn-down u-m-l-20" :class="filterOptions[selectedFilter].open?'up':'down'">
					<image :src="HTTP_IMG_URL()+'/static/images/arrow-down.png'" model="aspectFill"></image>
				</text>
			</picker>
		</view>
		<view style="background: #fff;border-top-right-radius:24rpx;border-top-left-radius: 24rpx; ">
			<!-- 资料区分 -->
			<view class="section-tabs">
				<view v-for="(section, idx) in sectionTabs" :key="section.value" :class="['section-tab', { active: currentSection === idx }]" @click="onSectionChange(section, idx)" class="u-flex u-flex-between u-flex-items-center">
					<image class="icon-content u-m-r-20" :src="HTTP_IMG_URL()+'/static/images/' + section.icon " mode="aspectFit"></image>
					<view class="u-flex u-flex-column u-flex-start u-flex-items-start">
						<text class="section-tab-label">{{ section.label }}</text>
						<text class="section-tabs-sub-label">{{ section.label }}</text>
					</view>
				</view>
			</view>
			
			<!-- 资料列表 -->
			<view class="resource-list">
				<view v-if="loading" class="loading-wrap">
					<uni-loading color="#3478f6" size="30" />
				</view>
				<view v-else-if="resourceList.length === 0" class="empty-wrap">
					<image :src="HTTP_IMG_URL()+'/static/images/empty.png'" class="empty-img" />
					<text class="empty-text">暂无相关资料</text>
				</view>
				<view v-else>
					<view v-for="item in resourceList" :key="item.id" class="resource-item u-flex u-flex-between u-flex-items-center">
						<view class="u-flex u-flex-column">
							<view class="resource-title">{{ item.name }}</view>
							<view class="resource-info">
								<text class="tag free" v-if="item.is_charge === 2">免费</text>
								<text class="size">{{ item.createtime }}</text>
								<text class="type">{{ item.type }}</text>
							</view>
						</view>
						<view class="download-btn" :class="{ downloading: showNoBuyModal&&downloadingId === item.id }" @click="downloadAndSaveFile(item.material)">
							下载
						</view>
					</view>
				</view>
			</view>
		</view>
	
		<!-- 未购买弹框 -->
		<view v-if="showBuyDialog" class="popup-mask">
			<view class="popup-dialog">
				<view class="popup-content">
					很抱歉，您还未购买相应课程，<br/>无法查看相关资料哦！
				</view>
				<view class="popup-actions">
					<view class="popup-btn" @click="cancelBuy">取消</view>
					<view class="popup-btn primary" @click="goBuy">去购买</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { record } from '@/api'
export default {
	data() {
		return {
			tabs: [],
			currentTab: 0,
			filterOptions: [
				{
					label: '全部',
					value: 'all',
				},
			],
			selectedFilter: 0,
			sectionTabs: [
				{
					label: '免费资料区',
					value: 'free',
					icon: 'ziliao/ziliao.png',
				},
				{
					label: '学员资料专区',
					value: 'member',
					icon: 'ziliao/xueyuan.png',
				}
			],
			currentSection: 0,
			resourceList: [],
			formData: {
				cid: '',
				is_charge: '2' // 1 收费 2 免费
			},
			loading: false,
			downloadingId: null,
			showNoBuyModal: false, // 控制未购买弹框
			showBuyDialog: false, // 是否已购买，后续可对接接口
			loadProgress: 0, //加载index
			dltDownLvNew:"", //已下载
			dltDownLvAll:"", //总长度
			dltDownLvWc:"", //完成率
			downloadUlr:"", //下载地址
			suffix:"", //文件后缀
		};
	},
	computed: {
		underlineStyle() {
			// Tab下划线动画
			const width = 100 / this.tabs.length;
			return `width: ${width}%; left: ${this.currentTab * width}%;`;
		},
	},
	methods: {
		HTTP_IMG_URL() {
			return this.$imgUrl;
		},
		onBack() {
			uni.navigateBack();
		},
		onTabChange(item, idx) {
			console.log(item, idx, 'item');
			this.formData.cid = item.id;
			this.currentTab = idx;
			this.refreshList();
		},
		onSectionChange(item, idx) {
			if (this.currentSection !== idx) {
				this.currentSection = idx;
			}
			if (item.value === 'free') {
				this.formData.is_charge = '2';
			} else{
				this.formData.is_charge = '1';
			}
			this.refreshList();
		},
		// 获取资料分类
		async getMaterialCategory () {
			const res = await record.getMaterialCategory().then((res) => {
				if (res.response.data.code == 1) {
					this.tabs = res.response.data.data;
					this.formData.cid = this.tabs[0].id;
					this.refreshList();
				}
			})
		},
		onFilterChange(e) {
			this.selectedFilter = e.detail.value;
			this.refreshList();
		},
		async refreshList() {
			this.loading = true;
			const res = await record.getMaterialList(this.formData).then((res) => {
				if (res.response.data.code == 1) {
					this.loading = false;
					this.resourceList = res.response.data.data.data;
					console.log(this.resourceList, 'this.resourceList');
				}
			})
		},
		downloadAndSaveFile(e){//点击下载
			let _this = this;
			//下载地址
			this.downloadUlr = e; 
			//获取地址后缀
			this.suffix = e.split(".")[e.split(".").length - 1];
			//判断是否为（图片或视频）
			if(e.substring(e.length - 3) == "MP4" || e.substring(e.length - 3) == "mp4" || e.substring(e.length - 3) == "jpg" || e.substring(e.length - 3) == "png"){
				const downloadTask = uni.downloadFile({
					url:e, 
					success: res => {
						if (res.statusCode === 200) {
							if(res.tempFilePath.substring(res.tempFilePath.length - 3) == "mp4" || res.tempFilePath.substring(res.tempFilePath.length - 3) == "MP4"){
								//保存视频到相册
								uni.saveVideoToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function () {
										uni.showToast({
											title: '保存成功',
											icon: 'none',
											duration:2000,
											mask:true
										});
									},
									fail: function() {
										this.loadProgress = 0;
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										});
									}
								});
							} else {//图片
								// 图片保存到手机相册
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function() {
										uni.showToast({
											title: '保存成功',
											icon: 'none',
											duration:2000,
											mask:true
										});
									},
									fail: function() {
										this.loadProgress = 0;
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										});
									}
								});
							}
						} else {
							uni.showToast({
								title:'下载失败',
								icon:"none"
							})
						}
					},
					fail:(err) => {
						this.loadProgress = 0;
						uni.showToast({
							icon:"none",
							mask:true,
							title:'下载失败'
						})
					}
				});
				downloadTask.onProgressUpdate((res) => {
					this.loadProgress = res.progress;
					if (this.loadProgress < 100) {
					} else {
						this.loadProgress = 0;
					}
					if(res.totalBytesExpectedToWrite < 10485760){
						this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
						this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
						this.dltDownLvWc = res.progress + "%"
					}else{
						this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
						this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
						this.dltDownLvWc = res.progress + "%"
					}
				});
			} else {
				//下载文件为非图片和视频的文件
				let _this = this;
				const downloadTaskt = uni.downloadFile({
					url:e,//下载地址接口返回
					success:(data) => {
						uni.hideLoading()
						if(data.statusCode === 200){
							var sFilePath = data.tempFilePath
							var sFileName = _this.downloadUlr.split('/')[_this.downloadUlr.split('/').length - 1];//原来的文件名
							
							//#ifdef APP-PLUS
								//文件保存到本地
								uni.saveFile({
									tempFilePath: data.tempFilePath,//临时路径
									success:function(res){
										
										var savedFilePath = res.savedFilePath;
										let osname = plus.os.name;
										//ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹，保存文件并改名
										if (osname == 'Android') {
											uni.showToast({
												icon:'none',
												mask:true, 
												title:'保存成功',
												duration:1000,
											});
											_this.fSetFileName(res.savedFilePath, sFilePath);
										}
										setTimeout(() => {
											//打开文档查看
											uni.openDocument({
												filePath:res.savedFilePath,
												success:function(res){
													// console.log("成功打开文件")
												},
												fail(){
													// console.log("打开文件失败")
												}
											})
										},1000)
									},
									fail:function(res){
										
									}
								});
							//#endif
							//#ifdef MP-WEIXIN
								//小程序对文件下载并不友好，不建议使用小程序当做下载器
								const FileSystemManager = wx.getFileSystemManager();
								FileSystemManager.saveFile({//下载成功后保存到本地
									tempFilePath:data.tempFilePath,
									filePath:wx.env.USER_DATA_PATH + "/" + sFileName,
									success(res2){
										if(res2.errMsg == 'saveFile:ok'){
											
											// 判断手机平台是 Android 还是 IOS
											if (uni.getSystemInfoSync().platform === 'android') {
												// console.log('运行Android上')
												uni.showModal({
													title:"保存地址为",
													content:"手机存储/Android/data/com.tencent.mm/MicroMsg/wxanewfiles"
												})
											} else {
												// console.log('运行iOS上')
												uni.showToast({
													title:"请转移APP下载",
													icon:"none"
												})
											}
											
										}else{
											uni.showToast({
												title:"下载失败",
												icon:"none"
											})
										}
									},
									fail(){
										uni.showToast({
											title:"下载失败",
											icon:"none"
										})
									}
								})
							//#endif
							
						}else{
							this.loadProgress = 0;
							uni.showToast({
								icon:"none",
								mask:true,
								title:"下载失败"
							})
						}
					},
					fail:(err) => {
						this.arcZzShow = false;
						this.loadProgress = 0;
						uni.showToast({
							icon:"none",
							mask:true,
							title:"下载失败"
						})
					}
				})
				downloadTaskt.onProgressUpdate((res) => {
					this.loadProgress = res.progress;
					if (this.loadProgress < 100) {
					} else {
						this.loadProgress = 0;
					}
					if(res.totalBytesExpectedToWrite < 10485760){
						this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
						this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
						this.dltDownLvWc = res.progress + "%"
					}else{
						this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
						this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
						this.dltDownLvWc = res.progress + "%"
					}
				});
			}
		},//点击下载END
		// 给下载的文件重命名
		fSetFileName(sFilePath, sFileName) {
			var sFileName = sFileName.split('/')[sFileName.split('/').length - 1];//原来的文件名
			
			var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1);//saveFile API保存的本地地址
			
			var url = this.downloadUlr;//下载地址
				// 'url下载地址（和上面的一样）'
			let dtask = plus.downloader.createDownload(url, {
					filename: "file://storage/emulated/0/AAA/" + sFileName //在手机存储更目录创建一个叫AAA的文件夹，把文件存储进去，并更改会原名
				},
				(d, status) => {
					if (status == 200) {
						let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
						
					} else {
						//下载失败
						plus.downloader.clear(); //清除下载任务
					}
				})
			dtask.start();
		},
		goBuy() {
			// 跳转到购买页面，留好口子
			this.showBuyDialog = false;
			uni.navigateTo({
				url: '/pages/pay/pay?courseId=' + this.downloadingId
			});
		},
		// 购买弹窗相关
		cancelBuy() {
			this.showBuyDialog = false;
		},
	},
	mounted() {
		this.getMaterialCategory();
	},
};
</script>

<style lang="scss">
.container {
	background: linear-gradient(180deg, #f8f9fb 60%, #eaf2ff 100%);
	min-height: 100vh;
	padding-bottom: 40rpx;
}
.nav-bar {
	display: flex;
	align-items: center;
	padding: 32rpx 24rpx 0 24rpx;
	background: #fff;
	border-bottom-left-radius: 32rpx;
	border-bottom-right-radius: 32rpx;
	box-shadow: 0 2rpx 8rpx #e5eaf3;
	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: 600;
		color: #222;
		letter-spacing: 2rpx;
	}
}
.tab-bar {
	display: flex;
	background: #fff;
	border-radius: 24rpx;
	margin-bottom: 20rpx;
	.tab-item {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 26rpx;
		color: #202020;
		border-bottom: 4rpx solid transparent;
	}
	.active {
		font-weight: bold;
		position: relative;
		color: #202020;
		font-weight: bold;
		&::after {
			width: 20rpx;
			position: absolute;
			content: "";
			bottom: 0;
			height: 6rpx;
			border-radius: 10rpx;
			background: #1976ff;
			left: 50%;
			transform: translateX(-50%);
		}
	}
}
.subject-select {
	margin: 0 auto;
	width: 90%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #f6f6f8;
	border-radius: 24rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	.label {
		font-size: 28rpx;
		color: #666;
		margin-right: 20rpx;
	}
	.picker {
		color: #1976ff;
	}
	.picker-value {
		color: #3a7afe;
		font-size: 28rpx;
	}
}

.section-tabs {
	display: flex;
	background:linear-gradient(180deg, #F5F5F5 60%, #fff 100%);;
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	margin: 0 24rpx 0rpx 24rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx #e5eaf3;
	.section-tab {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 28rpx 0;
		font-size: 28rpx;
		color: #666;
		background: #F5F5F5;
		font-weight: 500;
		transition: background 0.2s, color 0.2s;
		border-bottom-right-radius: 0rpx;
		border-bottom-left-radius: 24rpx;
		&.active {
			color: #fff;
			background: #fff;
			font-weight: 700;
			border-top-right-radius: 24rpx;
			border-bottom-right-radius: 0;
			border-bottom-left-radius: 0;
			
		}
		uni-icons {
			margin-right: 12rpx;
		}
		.icon-content{
			width: 60rpx;
			height: 60rpx;
		}
		.section-tab-label{
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 26rpx;
			color: #202020;
			line-height: 36rpx;
			text-align: left;
			font-style: normal;
		}
		.section-tabs-sub-label{
			font-family: PingFangSC, PingFang SC;
			font-size: 22rpx;
			color: #4A4A4A;
			line-height: 32rpx;
			text-align: left;
			font-style: normal;
		}
	}
}
.resource-list {
	margin: 0 24rpx;
	min-height: 400rpx;
	.loading-wrap {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 300rpx;
	}
	.empty-wrap {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 400rpx;
		margin-top: 200rpx;
		.empty-img {
			width: 40vw;
			height: 200rpx;
			margin-bottom: 24rpx;
		}
		.empty-text {
			color: #999;
			font-size: 28rpx;
		}
	}
	.resource-item {
		background: #fff;
		margin-bottom: 28rpx;
		padding: 40rpx 28rpx 36rpx 28rpx;
		position: relative;
		transition: box-shadow 0.2s;
		border-bottom: 1rpx solid #EEEEEE;
		&:active {
			box-shadow: 0 2rpx 8rpx #b0b8c6;
		}
		.resource-title {
			font-size: 28rpx;
			margin-bottom: 18rpx;
			color: #222;
		}
		.resource-info {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 18rpx;
			.tag.free {
				color: #3478f6;
				border: 1rpx solid #3478f6;
				border-radius: 8rpx;
				padding: 2rpx 16rpx;
				margin-right: 18rpx;
				font-size: 22rpx;
				background: #eaf2ff;
			}
			.size {
				margin-right: 18rpx;
			}
		}
		.download-btn {
			position: absolute;
			right: 32rpx;
			background: #1664FF;
			color: #fff;
			border-radius: 32rpx;
			font-size: 24rpx;
			padding: 12rpx 48rpx;
			box-shadow: 0 2rpx 8rpx #dbeaff;
			border: none;
			transition: background 0.2s, box-shadow 0.2s;
			&:active {
				background: linear-gradient(90deg, #245bb2 0%, #3478f6 100%);
				box-shadow: 0 1rpx 4rpx #b0b8c6;
			}
			&.downloading {
				opacity: 0.7;
			}
		}
	}
}
.picker-btn-down{
	 width: 20rpx;
	 height: 14rpx;
	 margin-left: 18rpx;
	margin-bottom: 3rpx;
	 display: inline-block;
	 background: url() no-repeat center;
	 background-size: 100%;
 }
.up{
	transform: rotate(180deg);
}
.down{
	transform: rotate(0deg);
}
.popup-mask {
	position: fixed;
	left: 0; top: 0; right: 0; bottom: 0;
	background: rgba(0,0,0,0.35);
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
}
.popup-dialog {
	background: #fff;
	border-radius: 24rpx;
	width: 80vw;
	max-width: 600rpx;
	padding: 48rpx 0 0 0;
	box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.08);
	display: flex;
	flex-direction: column;
	align-items: center;
}
.popup-content {
	font-size: 30rpx;
	color: #222;
	text-align: center;
	margin-bottom: 48rpx;
	line-height: 1.6;
}
.popup-actions {
	display: flex;
	width: 100%;
	border-top: 1rpx solid #eee;
}
.popup-btn {
	flex: 1;
	text-align: center;
	padding: 28rpx 0;
	font-size: 30rpx;
	color: #222;
	border-right: 1rpx solid #eee;
}
.popup-btn:last-child {
	border-right: none;
}
.popup-btn.primary {
	color: #1664FF;
	font-weight: bold;
}
.picker-btn-down{
	width: 20rpx;
	height: 14rpx;
	margin-left: 18rpx;
	image{
		width: 100%;
		height: 100%;
		margin-bottom: 20rpx ;
	}
}
</style>
